package com.example.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class MyController {


    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","Hello!Shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }
    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }
    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }
    @RequestMapping("/unauth")
    public String unauthorized(){
        return "unauth";
    }
    /**
     * 登录认证
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        //获取当前的用户
        Subject user = SecurityUtils.getSubject();
        System.out.println(user);
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            user.login(token);//执行登录的方法，如果没异常就登录成功了
            return "main";
        } catch (UnknownAccountException e) { //用户名不存在
            e.printStackTrace();
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){ //密码错误
            e.printStackTrace();
            model.addAttribute("msg","密码错误");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("msg","出现异常");
            return "login";
        }
    }
}
